package com.itheima.web.controller.store;

import com.itheima.core.BaseServlet;
import com.itheima.domain.store.QuestionItem;
import com.itheima.service.store.impl.QuestionItemServiceImpl;
import com.itheima.utils.BeanUtil;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@WebServlet("/store/questionItem/*")
public class QuestionItemServlet extends BaseServlet {
    private QuestionItemServiceImpl questionItemService = new QuestionItemServiceImpl();

    public Object list(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String questionId = request.getParameter("questionId");
        List<QuestionItem> list = questionItemService.findByQuestionId(questionId);
        request.setAttribute("list", list);
        request.setAttribute("questionId", questionId);
        return "/WEB-INF/pages/store/questionItem/list.jsp";
    }

    public Object saveOrUpdate(HttpServletRequest request, HttpServletResponse response) throws Exception {
        QuestionItem questionItem = BeanUtil.fillBean(request, QuestionItem.class);
        if (StringUtils.isBlank(questionItem.getId())) {
            //添加
            questionItemService.save(questionItem);
        } else {
            //修改
            questionItemService.update(questionItem);
        }

        return "/store/questionItem/list?questionId=" + questionItem.getQuestionId();
    }

    public Object toEdit(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String id = request.getParameter("id");
        QuestionItem questionItem = questionItemService.findById(id);
        request.setAttribute("questionItem", questionItem);
        return "/store/questionItem/list?questionId=" + questionItem.getQuestionId();
    }

    public Object delete(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String id = request.getParameter("id");
        String questionId = request.getParameter("questionId");
        questionItemService.deleteById(id);
        return "/store/questionItem/list?questionId=" + questionId;
    }
}
